import {messages, deepFullCopy} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, message, Upload, Modal, Button } from 'antd'
import AddTable from './add-table-cell'
import requestService from 'containers/request/request.service'
import httpFetch from "share/httpFetch"
import ExportModal from 'components/template/export-modal/export-modal'
import FileSaver from "file-saver"
import TableColumns from "containers/request/table.columns";

class ReceiverInformation extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
        data: [],
        loading: false,
        columns: [],
        columns1: [{
            title: <div className="red-with-star">所属机构/公司名称</div>,
            dataIndex: 'organization',
            width: '15%',
            editable: true,
            isRequired: true,
            inputType: 'input',
            trueTitle: '所属机构/公司名称'
          }, {
            title: <div className="red-with-star">职位</div>,
            dataIndex: 'position',
            width: '15%',
            editable: true,
            isRequired: true,
            inputType: 'input',
            trueTitle: '职位'
        }, {
            title: <div className="red-with-star">名称</div>,
            dataIndex: 'name',
            width: '15%',
            editable: true,
            isRequired: true,
            inputType: 'input',
            trueTitle: '名称'
        }, {
            title: <div className="red-with-star">金额</div>,
            dataIndex: 'amount',
            width: '15%',
            editable: true,
            isRequired: true,
            inputType: 'inputNumber',
            trueTitle: '金额'
        }],
        columns2: [{
          title: <div className="red-with-star">是否有政府人员参与</div>,
          dataIndex: 'governmentName',
          width: '15%',
          editable: true,
          isRequired: true,
          inputType: 'chooser',
          trueTitle: '是否有政府人员参与'
      }, {
          title: <div className="red-with-star">12个月内同一人超过2次</div>,
          dataIndex: 'isTwice',
          width: '15%',
          editable: true,
          isRequired: false,
          inputType: 'switch',
          trueTitle: '12个月内同一人超过2次'
      }, {
          title: '过去12个月内同一人超过2次的理由说明',
          dataIndex: 'remark',
          width: '15%',
          editable: false,
          isRequired: true,
          inputType: 'input',
          trueTitle: '过去12个月内同一人超过2次的理由说明'
      }],
      info: {},
      dataR: [],
      visible: false
    }
  }

  componentWillReceiveProps (nextProps) {
    if (this.state.info !== nextProps.info && this.props.totalAmount !== nextProps.totalAmount) {
      this.getTableColumns()
      this.getTableList()
    }
    this.setState({
      info: nextProps.info
    })
  }

  componentDidMount () {
    this.props.onRef(this)
    this.setState({
      info: this.props.info
    }, ()=> {
      this.getTableColumns()
      this.getGiftCardType()
      this.getTableList()
    })
  }

  getTableColumns() {
    let columns = []
    if (this.state.info.formCode === 'SQ003') {
      columns = TableColumns.SQ003.receive()
    } else {
      columns = TableColumns.default.receive(this)
    }
    console.log('dddd')
    this.setState({
      columns,
    })
  }

  // 获取接收人信息列表
  getTableList () {
    const {id, type} = this.props;
    this.setState({
      loading: true
    }, () => {
      requestService.getReceiverInfoList(id).then(res => {
        let data = deepFullCopy(res.data)
        const newData = data.map((item, index) => {
          item.key = new Date().getTime() + index
          item.isTwice = item.isTwice ? '是' : '否'
          return item
        })
        this.setState({
          data: newData,
          loading: false,
          dataR: res.data
        })
        if (type) {
          this.props.isCallBack({
            receiver: res.data,
            code: 'receiver'
          })
        }
      })
    })
  }

  // 获取礼品卡类型值列变OID以及获取礼品卡类型的数据
  getGiftCardType () {
    const isSQ003 = this.state.info.formCode === 'SQ003'
    const formType = isSQ003 ? 2 : 4;

    Promise.all([
      new Promise((resolve) => {
        requestService.getGiftCardType(4).then(res => {
          let customEnumerationOID = res.data[0].customEnumerationOID
          return requestService.getGiftCardTypeList(customEnumerationOID).then(data => {
            resolve(data)
          })
        })
      }),
      new Promise((resolve) => {
        requestService.getGiftCardType(isSQ003 ? 8 : 2, isSQ003 && '002').then(res => {
          let customEnumerationOID = res.data[0].customEnumerationOID
          return requestService.getGiftCardTypeList(customEnumerationOID).then(data => {
            resolve(data)
          })
        })
      })
    ]).then((res) => {
      const [data1, data2] = res
      const {columns} = this.state
      columns.map(item => {
        if (item.dataIndex === 'governmentName') {
          item.value = data1.data.code
        }
        if (this.state.info.formCode === 'SQ003' && item.dataIndex === 'giftType') {
          item.value = data2.data.values
        }
      })
      this.setState({
        columns
      })
    })

  }

  /**
   * 增加
   */
  handleOnAdd = (e) => {
    const { columns } = this.state
    // let index = columns.findIndex(item => item.dataIndex === 'remark')
    // columns[index].editable = false
    this.setState({
      columns
    }, () => {
      this.child.handleAdd()
    })
  }

  // 删除
  onDelete = (record) => {
    const { data, dataR } = this.state
    if (record.id) {
      requestService.receiverInfoListDelete(record.id).then(res => {
        if (res.data) {
          this.setState({
            data: data.filter(item => item.key !== record.key),
            dataR: dataR.filter(item => item.id !== record.id)
          },() => {
            message.success(messages('request.key780'/*删除成功*/))
            this.props.isCallBack(true)
          })
        }
      })
    } else {
      this.setState({ data: data.filter(item => item.key !== record.key) },() => {
        message.success(messages('request.key780'/*删除成功*/))
      })
    }
  }

  // 保存
  onSave = (value) => {
    this.setState({loading: true})
    const { record, index, row } = value
    const {formOID, id} = this.props;
    const { info } = this.state
    let json = {
      ...record,
      ...row,
    }
    if (info.formCode !== 'SQ004' && info.formCode !== 'SQ023') {
      if (row.governmentName && row.governmentName.length > 0) {
        json.governmentName = row.governmentName[0].messageKey
        json.governmentCode = row.governmentName[0].code
        if (row.governmentName[0].value) {
          json.isGovernment = row.governmentName[0].value === '016' ? 0 : 1
        } else {
          json.isGovernment = record.isGovernment ? 1 : 0
        }
      } else {
        json.governmentName = ''
        json.governmentCode = ''
        json.isGovernment = ''
      }
      json.isTwice = json.isTwice ? 1 : 0
      if (json.isTwice === 0) {
        json.remark = ''
      }
    } else {
      json.governmentName = ''
      json.governmentCode = ''
      json.isTwice = ''
    }

    if (info.formCode === 'SQ003') {
      if(json.quantity>99){
        message.warning('卡券数量不能超过99!')
        this.setState({loading: false})
        return
      }
      json.gift = record.gift ? record.gift.split(',')[0] : undefined
      json.giftType = row.giftType ? row.giftType.split(',')[0] : undefined
      json.unitPrice = value.unitPrice;
      if(json.releaseType){
        json.releaseType = json.releaseType.split(',')[0]
      }
    }
    if (record.id) {
      requestService.receiverInfoListEdit(json).then(res => {
        let data = deepFullCopy(res.data)
        data.isTwice = data.isTwice ? '是' : '否'
        this.onSaveFunc(record, index, data, res.data )
        message.success(messages('request.key779'/*保存成功*/))
      }).catch(() => {
        this.setState({loading: false})
      })
    } else {
      json.formOid = formOID
      json.applicationId = id
      requestService.receiverInfoListAdd(json).then(res => {
        let data = deepFullCopy(res.data)
        data.isTwice = data.isTwice ? '是' : '否'
        this.onSaveFunc(record, index, data, res.data )
        message.success(messages('request.key779'/*保存成功*/))
      }).catch(() => {
        this.setState({loading: false})
      })
    }
  }

  // 保存之后的回调
  onSaveFunc(record, index, row, data ) {
    const newData = [...this.state.data];
    const newDataR = [...this.state.dataR];
    row.key = new Date().getTime();
    newData.splice(index, 1, {
      ...record,
      ...row,
    })
    newDataR.splice(index, 1, data)
    this.setState({
      data: newData,
      loading: false,
      dataR: newDataR
    })
    this.child.cancel()
    this.props.isCallBack(true)
  }

  // 导入
  handleFileChange = (event) => {
    const files = event.fileList;
    if (files.length === 0) {
      return;
    }
    const file = files[0];
    const form = new FormData();
    form.append("file", file);
    const {formOID, id} = this.props;
    httpFetch
      .post(`/api/gift/receiver/import?formOid=${formOID}&applicationId=${id}&language=zh_cn`, form)
      .then((res) => {
        const rows = res.data.rows || []
        let trueRows = rows.filter(item => !item.error)
        let errorRows = rows.filter(item => item.error)
        this.setState({visible: false})
        this.getTableList()
        if (errorRows && errorRows[0]) {
          message.warning(errorRows[0].error);
        } else {
          message.success(`本次导入${trueRows.length}条数据`);
        }
      }).catch(err=>{
        if(err.response.data&&err.response.data.message){
          message.error(err.response.data.message)
        }
      })
  }

  // 下载模板
  handleDownloadTemplate = () => {
    let { info } = this.state
    let { formCode, id } = info
    let url = '/api/gift/receiver/template/download?roleType=TENANT'
    let name = '礼品接收人清单模板'
    if (formCode === 'SQ004') {
      url = '/api/gift/receiver/GH/template/download?roleType=TENANT'
    } else if (formCode === 'SQ003') {
      url += `&applicationId=${id}`
    }
    requestService.downloadTemplate('get', url, {}).then((res) => {
      let file = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
      let contentDisposition = res.headers['content-disposition']
      let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
      let matches = filenameRegex.exec(contentDisposition)
      let fieldName = ''
      if (matches != null && matches[1]) {
        fieldName = matches[1].replace(/['"]/g, '')
      }
      fieldName = decodeURIComponent(escape(fieldName))
      FileSaver.saveAs(file, `${fieldName}.xlsx`);
    })
  }

  handleShowModal = () => {
    this.setState({ visible: true });
  }

  handleCancel = () => {
    this.setState({ visible: false });
  }

  render() {
    const { data, loading, info, columns, visible } = this.state
    const { isDoneApproved } = this.props;
    const isEdit = ['10011000', '10011001', '10011002'].includes(`${info.status}${info.rejectType}`) && ['SQ002', 'SQ003', 'SQ004'].includes(info.formCode) ? isDoneApproved && isDoneApproved === 'true' ? false : true : false
    let exportCommand = '礼品接收人清单'
    const title = (
      <div className="sub-header-receiverInformation-title">
          <span className="receiverInformation-title">{messages('request.key764'/*接收人信息*/)}</span>
          {
            isEdit && (<span className="receiverInformation-btn" onClick={this.handleOnAdd}>{messages('request.key763'/*+新增*/)}</span>)
          }
          {
            isEdit && (
              <span className="receiverInformation-btn" onClick={this.handleDownloadTemplate}>下载模板</span>
            )
          }
          {
            isEdit && data.length > 0 && (
              <span className="receiverInformation-btn" onClick={this.handleShowModal}> 导入</span>
            )
          }
          {
            isEdit && data.length <= 0 && (
              <span className="receiverInformation-btn" style={{display: 'inline-block'}}>
                <Upload
                  multiple={false}
                  accept=".xls,.xlsx"
                  beforeUpload={() => false}
                  onChange={this.handleFileChange}
                >
                  <span style={{color: '#007AFF', fontSize: '12px'}}>
                    导入
                  </span>
                </Upload>
              </span>
            )
          }
          <span className="receiverInformation-btn" style={{display: 'inline-block'}}>
            <ExportModal
                exportTitle={`导出`}
                exportType="GIFT_RECEIVER"
                exportCommand={exportCommand}
                exportCondition={{giftReceiverDownloadCommand: {applicationId: info.id}}}
            />
          </span>
      </div>
    )
    return (
      <div className="request-info" style={{paddingTop: '20px'}}>
        <div className="tab-container">
            <AddTable
              onRef={ref => this.child = ref}
              value={data}
              isEdit={isEdit}
              loading={loading}
              columns={columns}
              operationKey={"receiver"}
              onDelete={this.onDelete}
              onChange={this.onChange}
              onSave={this.onSave}
              title={() => (title)}
            />
        </div>
        <Modal
          title="友情提示"
          visible={visible}
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel} style={{marginRight: '15px'}}>
              取消
            </Button>,
            <Upload
              key="upload"
              multiple={false}
              accept=".xls,.xlsx"
              beforeUpload={() => false}
              onChange={this.handleFileChange}
            >
              <Button type="primary">
                确定导入
              </Button>
            </Upload>
          ]}
        >
          <p>导入人员清单，历史导入的数据会自动清空，请确保最新导入数据完整无误，是否导入？</p>
        </Modal>
      </div>
    )
  }
}

ReceiverInformation.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return { }
}

const wrappedReceiverInformation = Form.create()(ReceiverInformation);

export default connect(mapStateToProps)(wrappedReceiverInformation)
